using System;
using System.Collections.Generic;
using UnityEngine;

namespace Jerry.UiFrame
{
    public class TimerManager : MonoBehaviour
    {
        private static TimerManager instance;
        private readonly HashSet<Timer> _activeTimers = new(); //激活中的定时器
        private readonly Queue<Timer> _timersToAdd = new(); //添加定时器队列
        private int _timerId;

        private void Update()
        {
            foreach (var timer in _timersToAdd) _activeTimers.Add(timer);
            _timersToAdd.Clear();

            var deltaTime = Time.deltaTime;
            var unscaledDelta = Time.unscaledDeltaTime;

            var completedTimers = new List<Timer>();
            foreach (var timer in _activeTimers)
            {
                if (timer.IsDone)
                {
                    completedTimers.Add(timer);
                    continue;
                }

                var delta = timer.BUseUnscaledTime ? unscaledDelta : deltaTime;
                timer.Update(delta);

                if (timer.IsDone) completedTimers.Add(timer);
            }

            // 移除已完成定时器
            foreach (var timer in completedTimers) _activeTimers.Remove(timer);
        }

        public static Timer AddTimer(float duration, Action onComplete, bool bLoop = false,
            bool bUseUnscaledTime = false)
        {
            var timer = new Timer(duration, onComplete, bLoop, bUseUnscaledTime);
            RegisterTimer(timer);
            return timer;
        }

        public static void CreateInstance()
        {
            var go = new GameObject("TimerManager");
            instance = go.AddComponent<TimerManager>();

            DontDestroyOnLoad(go);
        }

        /// <summary>
        ///     停止指定的定时器
        /// </summary>
        /// <param name="timer"></param>
        public static void StopTimer(Timer timer)
        {
            foreach (var t in instance._activeTimers)
                if (t.Id == timer.Id)
                    t.Stop();
        }

        /// <summary>
        ///     暂停指定定时器
        /// </summary>
        /// <param name="timer"></param>
        public static void PauseTimer(Timer timer)
        {
            foreach (var t in instance._activeTimers)
                if (t.Id == timer.Id && !t.IsPaused)
                    t.Pause();
        }

        /// <summary>
        ///     恢复暂停的定时器
        /// </summary>
        /// <param name="timer"></param>
        public static void ResumeTimer(Timer timer)
        {
            foreach (var t in instance._activeTimers)
                if (t.Id == timer.Id && t.IsPaused)
                    t.Resume();
        }

        private static void RegisterTimer(Timer timer)
        {
            if (!instance)
                CreateInstance();

            timer.Id = ++instance._timerId;
            instance._timersToAdd.Enqueue(timer);
        }
    }
}